#!/usr/bin/perl

use strict;

use LWP::UserAgent;
use HTTP::Request::Common;
use HTTP::Request::Common qw(DELETE);
use MIME::Base64;
use XML::Simple;
use Data::Dumper;
use Getopt::Long;

local $SIG{__WARN__} = sub { };

my $server;
my $organization;
my $user;
my $orgvdc;
my $vappname;
my $debug;

if ( @ARGV > 0 ) {
  GetOptions('s|server=s' => \$server,
             'o|organization=s' => \$organization,
             'u|user=s' => \$user,
             'v|orgvdc=s' => \$orgvdc,
             'n|vappname=s' => \$vappname,
             'd|debug' => \$debug);
}
unless ($server && $organization && $user && $orgvdc && $vappname) {
  print "Usage: delete.pl --server SERVER --organization ORGANIZATION --user USER --orgvdc ORGVDC --vappname VAPPNAME [--debug]\n";
  print "...or  delete.pl -s SERVER -o ORGANIZATION -u USER -v ORGVDC -n VAPPNAME [-d]\n";
  exit;
}

my $version = "v1.0";
my $vcdurl = "https://" . $server . "/api/$version";
my $vcdpass;
my $trk_loaded = 0;
# "use" loads modules at compile-time. Since Term::ReadKey is used
# if it is installed, but there's no problem if not, we "require"
# instead and import their symbols by hand if successful.
#
# See perldoc -f require and perldoc -q require for further details.
eval {
  require Term::ReadKey;
  import Term::ReadKey;
  $trk_loaded = 1;
};
print 'vDC password: ';
ReadMode('noecho') if $trk_loaded;  # input echo off
chomp($vcdpass = $trk_loaded ? ReadLine(0) : <STDIN>);
ReadMode('restore') if $trk_loaded; # input echo on
print "\n";

my $xml;
my $response;

# create browser with cookies enabled in memory only
# cookies are required because the vCloud Director server issues a 
# session cookie which must be submitted with every subsequent request

my $userAgent = LWP::UserAgent->new(agent => 'perl LWP', cookie_jar => {});

# login with the supplied credentials

my $cryptAuth = encode_base64($user . "@" . $organization . ":" . $vcdpass);

$response = $userAgent->request(POST $vcdurl . '/login',
                        Content_Type => 'text/xml',
                        Authorization => 'Basic ' . $cryptAuth);

unless (  $response->is_success ) {
  die $response->as_string;
}

if ( $debug ) {
  print "login successful.\n";
  print $response->content;
}

# browse the organization to find the Catalog and OrgVDC

$xml = XMLin($response->content, KeyAttr => [ ], ForceArray => 1);

my $orgRef = "";
my $vdcRef = "";

foreach my $org (@{$xml->{Org}}) {
  if ( $org->{name} eq $organization) {
      $orgRef = $org->{href};
  }
}

if ($orgRef) {
  print "$orgRef\n" if ($debug);
}
else {
  die "$organization not found!\n";
}

$response = $userAgent->request(GET $orgRef);

unless (  $response->is_success ) {
  die $response->as_string;
}

if ( $debug ) {
  print $response->content;
}

$xml = XMLin($response->content);

foreach my $link (@{$xml->{Link}}) {
  if ( $link->{type} eq 'application/vnd.vmware.vcloud.vdc+xml' ) {
    if ( $link->{name} eq $orgvdc) {
      $vdcRef = $link->{href};
    }
  }
}

unless ( $vdcRef ne "" ) {
  die ("OrgVDC $orgvdc not found!\n");
}

if ( $debug ) { print "OrgVDC: $vdcRef\n"; }

# find the vApp

$response = $userAgent->request(GET $vdcRef);

unless (  $response->is_success ) {
  die $response->as_string;
}

if ( $debug ) {
  print $response->content;
}

$xml = XMLin($response->content, KeyAttr => [ ], ForceArray => 1);

my $vappRef;

foreach my $resEnt (@{$xml->{ResourceEntities}[0]->{ResourceEntity}}) {
  if ( $resEnt->{type} eq "application/vnd.vmware.vcloud.vApp+xml" && $resEnt->{name} eq $vappname) {
      $vappRef = $resEnt->{href};
  }
}

if ($vappRef) {
  print "$vappRef\n" if ($debug);
}
else {
  die "$vappname not found!\n";
}

# delete the vApp

if ($debug) { print "DELETE " . $vappRef . "\n"; }

$response = $userAgent->request(DELETE $vappRef);

unless (  $response->is_success ) {
  print $response->as_string if ( $debug );
  $xml = XMLin($response->content);
  print $xml->{message}."\n";
  logout();
  exit;
}
if ( $debug ) {
  print $response->content;
}

print "vApp delete complete.\n";

# logout

logout();

sub logout() {
  $response = $userAgent->request(POST $vcdurl . '/logout');
  
  if ( $debug ) {
    print "POST ".$vcdurl."/logout\n";
    print $response->content;
  }
  unless (  $response->is_success ) {
    die $response->as_string;
  }
  
  if ( $debug ) { print "logout successful.\n"; }
}
